package com.littleken.demo.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.littleken.demo.dto.User;
import com.littleken.demo.dto.UserQueryCondition;
import com.littleken.demo.exception.UserNotExistException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Pageable;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户controller
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class userController {



    @JsonView(User.UserSimpleView.class)//不显示密码
    @GetMapping
    public List<User> query(UserQueryCondition condition
            , @PageableDefault(page = 2,size = 17,sort = "username,asc") Pageable pageable){

        List<User> userList = new ArrayList<>();

        User user = User.builder().username("邝").password("123465798").build();

        for (int i = 0; i < 3; i++) {
            userList.add(user);
        }

        return userList;
    }


    //@GetMapping("/{id}")
    @GetMapping("/{id:\\d+}")//
    @JsonView(User.UserDetailView.class)//显示密码
    public User getInfo(/*@ApiParam("用户id") @PathVariable */
            @PathVariable String id) {
        throw new UserNotExistException(id);
       /* User user = new User();
        user.setUsername("tom");
        user.setPassword("123465");
        return user;*/
    }

    @PostMapping
    public User create(@Valid @RequestBody User user
    ,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("参数不正确, 信息 ： {}",bindingResult.getFieldError().getDefaultMessage());
        }
        user.setId("1");
        return user;
    }

    @PutMapping("/{id:\\d+}")
    public User update(@Valid @RequestBody User user
            ,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("参数不正确, 信息 ： {}",bindingResult.getFieldError().getDefaultMessage());
        }
        user.setId("1");
        return user;
    }


    @DeleteMapping("/{id:\\d+}")
    public void delete(@PathVariable String id) {
        System.out.println(id);
    }

}
